<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧工具栏 -->
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>设计工具</span>
            </div>
          </template>
          <!-- 问卷基本信息表单放在这里 -->
          <el-form :model="questionnaireForm" :rules="formRules" ref="questionnaireFormRef" label-width="80px" size="small">
            <el-form-item label="问卷标题" prop="title">
              <el-input v-model="questionnaireForm.title" placeholder="请输入问卷标题" />
            </el-form-item>
            <el-form-item label="问卷描述" prop="description">
              <el-input v-model="questionnaireForm.description" type="textarea" placeholder="请输入问卷描述" />
            </el-form-item>
          </el-form>
          <!-- 题目类型选择 -->
          <el-divider content-position="left">添加题目</el-divider>
          <div class="question-types">
            <el-button 
              v-for="type in questionTypes" 
              :key="type.value"
              type="primary" 
              plain 
              size="small"
              @click="addQuestion(type.value)"
              style="margin: 5px;"
            >
              {{ type.label }}
            </el-button>
          </div>
          <!-- 模板选择 -->
          <el-divider content-position="left">问卷选择</el-divider>
          <el-select v-model="selectedQuestionnaireId" placeholder="选择问卷" style="width: 100%" @change="handleQuestionnaireChange">
            <el-option v-for="item in questionnaireOptions" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
          <!-- 操作按钮 -->
          <el-divider content-position="left">操作</el-divider>
          <div class="action-buttons">
            <el-button type="primary" @click="saveDesign" :loading="saving" style="width: 100%;">保存设计</el-button>
            <el-button type="success" @click="previewDesign" style="width: 100%;">预览问卷</el-button>
          </div>
        </el-card>
      </el-col>
      
      <!-- 中间设计区域 -->
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>问卷设计区域</span>
              <el-button type="primary" size="small" @click="addQuestion('single')">添加题目</el-button>
            </div>
          </template>
          
          <div class="design-area">
            <div v-if="questions.length === 0" class="empty-state">
              <el-empty description="暂无题目，请添加题目开始设计" />
            </div>
            
            <div v-else class="questions-list">
              <div 
                v-for="(question, index) in questions" 
                :key="question.id || index"
                class="question-item"
                :class="{ 'active': activeQuestionIndex === index }"
                @click="selectQuestion(index)"
              >
                <div class="question-header">
                  <span class="question-number">Q{{ index + 1 }}</span>
                  <span class="question-type">{{ getQuestionTypeLabel(question.questionType) }}</span>
                  <div class="question-actions">
                    <el-button link size="small" @click.stop="moveQuestion(index, -1)" :disabled="index === 0">
                      <el-icon><ArrowUp /></el-icon>
                    </el-button>
                    <el-button link size="small" @click.stop="moveQuestion(index, 1)" :disabled="index === questions.length - 1">
                      <el-icon><ArrowDown /></el-icon>
                    </el-button>
                    <el-button link size="small" @click.stop="deleteQuestion(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="question-content">
                  <el-input v-model="question.content" placeholder="请输入题目内容" />
                </div>
                
                <!-- 选项编辑区域 -->
                <div v-if="question.questionType !== 'text'" class="options-area">
                  <div class="options-header">
                    <span>选项</span>
                    <el-button link size="small" @click="addOption(index)">
                      <el-icon><Plus /></el-icon>添加选项
                    </el-button>
                  </div>
                  <div class="options-list">
                    <div 
                      v-for="(option, optionIndex) in question.options" 
                      :key="optionIndex"
                      class="option-item"
                    >
                      <el-input 
                        v-model="option.optionLabel" 
                        placeholder="选项内容"
                        size="small"
                        style="width: 80%"
                      />
                      <el-button link size="small" @click="deleteOption(index, optionIndex)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
                
                <!-- 题目设置 -->
                <div class="question-settings">
                  <el-checkbox v-model="question.required">必填题目</el-checkbox>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧预览区域 -->
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>实时预览</span>
            </div>
          </template>
          
          <div class="preview-area">
            <div class="preview-questionnaire">
              <div class="preview-header">
                <h3 class="preview-title">{{ questionnaireForm.title || '问卷标题' }}</h3>
                <p class="preview-description">{{ questionnaireForm.description || '问卷描述' }}</p>
                <div class="preview-meta">
                  <span class="question-count">共 {{ questions.length }} 道题目</span>
                </div>
              </div>
              
              <div class="preview-questions">
                <div v-for="(question, index) in questions" :key="index" class="preview-question-item">
                  <div class="question-header">
                    <span class="question-number">{{ index + 1 }}</span>
                    <span class="question-title">{{ question.content || '题目内容' }}</span>
                    <el-tag v-if="question.required" type="danger" size="small" class="required-tag">必填</el-tag>
                    <el-tag type="info" size="small" class="type-tag">
                      {{ getQuestionTypeLabel(question.questionType) }}
                    </el-tag>
                  </div>
                  
                  <div class="question-content">
                    <!-- 单选题 -->
                    <div v-if="question.questionType === 'single'" class="options-container">
                      <el-radio-group v-model="previewAnswers[index]">
                        <div v-for="option in (question.options || [])" :key="option.optionValue" class="option-item">
                          <el-radio :value="option.optionValue">
                            {{ option.optionLabel }}
                          </el-radio>
                        </div>
                      </el-radio-group>
                    </div>
                    
                    <!-- 多选题 -->
                    <div v-else-if="question.questionType === 'multiple'" class="options-container">
                      <el-checkbox-group v-model="previewAnswers[index]">
                        <div v-for="option in (question.options || [])" :key="option.optionValue" class="option-item">
                          <el-checkbox :value="option.optionValue">
                            {{ option.optionLabel }}
                          </el-checkbox>
                        </div>
                      </el-checkbox-group>
                    </div>
                    
                    <!-- 文本题 -->
                    <div v-else-if="question.questionType === 'text'" class="text-container">
                      <el-input 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入您的答案" 
                        class="text-input"
                      />
                    </div>
                    
                    <!-- 无选项时显示提示（仅对单选题和多选题） -->
                    <div v-if="(question.questionType === 'single' || question.questionType === 'multiple') && (!question.options || question.options.length === 0)" class="no-options">
                      <el-empty description="暂无选项" :image-size="60" />
                    </div>
                  </div>
                </div>
                
                <div v-if="questions.length === 0" class="no-questions">
                  <el-empty description="该问卷暂无题目" :image-size="100" />
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="问卷预览" width="80%" append-to-body>
      <div class="preview-dialog-content">
        <div class="preview-header">
          <h2 class="preview-title">{{ questionnaireForm.title || '未命名问卷' }}</h2>
          <p class="preview-description">{{ questionnaireForm.description || '暂无描述' }}</p>
          <div class="preview-meta">
            <span class="question-count">共 {{ questions.length }} 道题目</span>
          </div>
        </div>
        
        <div class="preview-questions">
          <div v-for="(question, index) in questions" :key="question.id || index" class="preview-question-item">
            <div class="question-header">
              <span class="question-number">{{ index + 1 }}</span>
              <span class="question-title">{{ question.content || '未命名题目' }}</span>
              <el-tag v-if="question.required" type="danger" size="small" class="required-tag">必填</el-tag>
              <el-tag type="info" size="small" class="type-tag">
                {{ getQuestionTypeLabel(question.questionType) }}
              </el-tag>
            </div>
            
            <div class="question-content">
              <!-- 单选题 -->
              <div v-if="question.questionType === 'single'" class="options-container">
                <el-radio-group v-model="previewAnswers[index]">
                  <div v-for="option in (question.options || [])" :key="option.optionValue" class="option-item">
                    <el-radio :value="option.optionValue">
                      {{ option.optionLabel }}
                    </el-radio>
                  </div>
                </el-radio-group>
              </div>
              
              <!-- 多选题 -->
              <div v-else-if="question.questionType === 'multiple'" class="options-container">
                <el-checkbox-group v-model="previewAnswers[index]">
                  <div v-for="option in (question.options || [])" :key="option.optionValue" class="option-item">
                    <el-checkbox :value="option.optionValue">
                      {{ option.optionLabel }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
              
              <!-- 文本题 -->
              <div v-else-if="question.questionType === 'text'" class="text-container">
                <el-input 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入您的答案" 
                  class="text-input"
                />
              </div>
              
              <!-- 无选项时显示提示（仅对单选题和多选题） -->
              <div v-if="(question.questionType === 'single' || question.questionType === 'multiple') && (!question.options || question.options.length === 0)" class="no-options">
                <el-empty description="暂无选项" :image-size="60" />
              </div>
            </div>
          </div>
          
          <div v-if="questions.length === 0" class="no-questions">
            <el-empty description="该问卷暂无题目" :image-size="100" />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveDesign" :loading="saving">
            保存设计
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown, Delete, Plus } from '@element-plus/icons-vue'
import { getDesignData, getDraftQuestionnaires, saveQuestionnaireDesign } from '@/api/questionnaire'

const { proxy } = getCurrentInstance()

// 获取路由信息
const route = useRoute()

// 响应式数据
const questionnaireForm = reactive({
  title: '',
  description: ''
})

const questions = ref([])
const activeQuestionIndex = ref(-1)
const selectedQuestionnaireId = ref('new')
const questionnaireOptions = ref([])
const saving = ref(false)
const previewDialogVisible = ref(false)
const previewAnswers = ref({})

// 题目类型定义
const questionTypes = [
  { label: '单选题', value: 'single' },
  { label: '多选题', value: 'multiple' },
  { label: '文本题', value: 'text' }
]

// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请输入问卷标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入问卷描述', trigger: 'blur' }]
}

// 表单引用
const questionnaireFormRef = ref(null)

// 计算属性
const getQuestionTypeLabel = (type) => {
  const found = questionTypes.find(t => t.value === type)
  if (found) {
    return found.label
  }
  // 处理数据库中的 'multiple' 类型
  if (type === 'multiple') {
    return '多选题'
  }
  return type
}

// 方法
const updateQuestionOrder = () => {
  questions.value.forEach((q, i) => {
    q.orderNum = i + 1
  })
}

const addQuestion = (type) => {
  const newQuestion = {
    // id: Date.now(), // 移除前端生成id，交由后端生成
    questionType: type,
    content: '',
    required: true,
    orderNum: questions.value.length + 1, // 从1开始
    options: type !== 'text' ? [
      { optionLabel: '选项1', optionValue: 'option1', orderNum: 1 },
      { optionLabel: '选项2', optionValue: 'option2', orderNum: 2 }
    ] : []
  }
  questions.value.push(newQuestion)
  updateQuestionOrder()
  activeQuestionIndex.value = questions.value.length - 1
}

const selectQuestion = (index) => {
  activeQuestionIndex.value = index
}

const deleteQuestion = (index) => {
  ElMessageBox.confirm('确定要删除这个题目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    questions.value.splice(index, 1)
    updateQuestionOrder()
    if (activeQuestionIndex.value >= questions.value.length) {
      activeQuestionIndex.value = questions.value.length - 1
    }
    ElMessage.success('删除成功')
  })
}

const moveQuestion = (index, direction) => {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < questions.value.length) {
    const temp = questions.value[index]
    questions.value[index] = questions.value[newIndex]
    questions.value[newIndex] = temp
    updateQuestionOrder()
    activeQuestionIndex.value = newIndex
  }
}

const addOption = (questionIndex) => {
  const question = questions.value[questionIndex]
  const newOption = {
    optionLabel: `选项${question.options.length + 1}`,
    optionValue: `option${question.options.length + 1}`,
    orderNum: question.options.length + 1
  }
  question.options.push(newOption)
}

const deleteOption = (questionIndex, optionIndex) => {
  questions.value[questionIndex].options.splice(optionIndex, 1)
}

const loadTemplate = (templateId) => {
  // 这里可以根据模板ID加载预设的题目
  console.log('加载模板:', templateId)
}

const saveDesign = async () => {
  if (!questionnaireFormRef.value) return
  await questionnaireFormRef.value.validate((valid) => {
    if (valid) {
      if (!questionnaireForm.title.trim()) {
        ElMessage.warning('请输入问卷标题')
        return
      }
      // 提交前统一更新orderNum
      updateQuestionOrder()
      saving.value = true
      try {
        // 组装DTO结构
        const dto = {
          questionnaire: {
            ...questionnaireForm,
            status: 'draft', // 自动附加草稿状态
          },
          questions: questions.value.map(q => ({
            ...q,
            orderNum: q.orderNum, // 明确传递从1开始的orderNum
            optionList: (q.options || []).map((opt, idx) => ({
              ...opt,
              orderNum: idx + 1
            }))
          }))
        };
        saveQuestionnaireDesign(dto);
        ElMessage.success('保存成功')
      } catch (error) {
        ElMessage.error('保存失败：' + error.message)
      } finally {
        saving.value = false
      }
    } else {
      ElMessage.error('请检查表单填写')
    }
  })
}

const previewDesign = () => {
  previewDialogVisible.value = true
}

// 加载草稿问卷列表
const loadQuestionnaireOptions = async () => {
  const res = await getDraftQuestionnaires()
  questionnaireOptions.value = [{ id: 'new', title: '新问卷' }, ...(res.data || [])]
}

// 选择问卷切换
const handleQuestionnaireChange = async (id) => {
  if (id === 'new') {
    Object.assign(questionnaireForm, { title: '', description: '' })
    questions.value = []
  } else {
    const res = await getDesignData(id)
    if (res.data) {
      Object.assign(questionnaireForm, res.data.questionnaire)
      questions.value = res.data.questions || []
    }
  }
}

// 生命周期
onMounted(async () => {
  await loadQuestionnaireOptions()
  selectedQuestionnaireId.value = 'new'
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-types {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
  width: 100%;
  padding: 0;
}

.action-buttons .el-button {
  width: 100%;
  margin: 0;
  box-sizing: border-box;
}

.design-area {
  min-height: 400px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.question-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.question-item:hover {
  border-color: #409eff;
}

.question-item.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.question-number {
  font-weight: bold;
  margin-right: 10px;
  color: #409eff;
}

.question-type {
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: auto;
}

.question-actions {
  display: flex;
  gap: 5px;
}

.question-content {
  margin-bottom: 15px;
}

.options-area {
  margin-bottom: 15px;
}

.options-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.question-settings {
  border-top: 1px solid #e4e7ed;
  padding-top: 10px;
}

.preview-area {
  max-height: 600px;
  overflow-y: auto;
}

.preview-questionnaire {
  padding: 10px;
}

.preview-questionnaire .preview-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-questionnaire .preview-title {
  color: #303133;
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: bold;
}

.preview-questionnaire .preview-description {
  color: #606266;
  margin-bottom: 10px;
  line-height: 1.5;
  font-size: 13px;
}

.preview-questionnaire .preview-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.preview-questionnaire .question-count {
  color: #909399;
  font-size: 11px;
}

.preview-questionnaire .preview-questions {
  margin-top: 15px;
}

.preview-questionnaire .preview-question-item {
  margin-bottom: 15px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.preview-questionnaire .preview-question-item:hover {
  border-color: #409eff;
  box-shadow: 0 1px 4px rgba(64, 158, 255, 0.1);
}

.preview-questionnaire .question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 8px;
}

.preview-questionnaire .question-number {
  background-color: #409eff;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: bold;
}

.preview-questionnaire .question-title {
  flex: 1;
  font-weight: bold;
  color: #303133;
  font-size: 14px;
}

.preview-questionnaire .required-tag {
  margin-left: auto;
}

.preview-questionnaire .type-tag {
  margin-left: 3px;
}

.preview-questionnaire .question-content {
  margin-left: 28px;
}

.preview-questionnaire .options-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-questionnaire .option-item {
  padding: 6px 10px;
  border-radius: 3px;
  background-color: white;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.preview-questionnaire .option-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.preview-questionnaire .text-container {
  margin-top: 8px;
}

.preview-questionnaire .text-input {
  width: 100%;
}

.preview-questionnaire .no-options {
  text-align: center;
  padding: 15px;
  color: #909399;
}

.preview-questionnaire .no-questions {
  text-align: center;
  padding: 30px;
  color: #909399;
}

/* 预览对话框样式 */
.preview-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

.preview-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.preview-title {
  color: #303133;
  margin-bottom: 10px;
  font-size: 24px;
  font-weight: bold;
}

.preview-description {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
  font-size: 14px;
}

.preview-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.question-count {
  color: #909399;
  font-size: 12px;
}

.preview-questions {
  margin-top: 20px;
}

.preview-question-item {
  margin-bottom: 25px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.preview-question-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.question-number {
  background-color: #409eff;
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.question-title {
  flex: 1;
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.required-tag {
  margin-left: auto;
}

.type-tag {
  margin-left: 5px;
}

.question-content {
  margin-left: 34px;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  padding: 8px 12px;
  border-radius: 4px;
  background-color: white;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.option-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.text-container {
  margin-top: 10px;
}

.text-input {
  width: 100%;
}

.no-options {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-questions {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style> 